
package com.jf.cloud.search.listener;

import cn.throwx.canal.gule.model.CanalBinLogResult;
import com.jf.cloud.api.product.feign.ProductFeignClient;
import com.jf.cloud.common.cache.constant.CacheNames;
import com.jf.cloud.common.cache.util.CacheManagerUtil;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.product.bo.EsProductBO;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.search.bo.SpuTagBO;
import com.jf.cloud.search.util.EsSearchUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Objects;


/**
 * @author zz
 * @date 2021/01/21
 */
@Component
public class SpuTagCanalListener extends BaseCanalBinlogEventThrowExceptionProcessor<SpuTagBO> {

    private static final Logger log = LoggerFactory.getLogger(SpuTagCanalListener.class);

    @Autowired
    private ProductFeignClient productFeignClient;
    @Autowired
    private CacheManagerUtil cacheManagerUtil;

    @Override
    protected void processInsertInternal(CanalBinLogResult<SpuTagBO> result) {
        updateSpuTagData(result);
    }

    @Override
    protected void processUpdateInternal(CanalBinLogResult<SpuTagBO> result) {
        SpuTagBO beforeData = result.getBeforeData();
        if (Objects.isNull(beforeData.getSeq())) {
            return;
        }
        updateSpuTagData(result);
    }

    @Override
    protected void processDeleteInternal(CanalBinLogResult<SpuTagBO> result) {
        updateSpuTagData(result);
    }

    private void updateSpuTagData(CanalBinLogResult<SpuTagBO> result) {
        SpuTagBO afterData = result.getAfterData();
        cacheManagerUtil.evictCache(CacheNames.SPU_TAG_BY_SHOP, afterData.getShopId().toString());

        ServerResponseEntity<List<Long>> spuTagResponse = productFeignClient.getSpuTagBySpuId(afterData.getSpuId());
        if (spuTagResponse.isFail()) {
            throw new LuckException(spuTagResponse.getMsg());
        }
        EsProductBO esProductBO = new EsProductBO();
        esProductBO.setTagIds(spuTagResponse.getData());
        List<Long> spuIds = Collections.singletonList(afterData.getSpuId());
        EsSearchUtil.esUpdateSpuBySpuIds(spuIds, esProductBO);
    }
}
